package com.dms.modules.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.security.JwtTokenProvider;
import com.dms.modules.admin.dto.AdminCreateDTO;
import com.dms.modules.admin.dto.AdminLoginRequest;
import com.dms.modules.admin.dto.AdminLoginResponse;
import com.dms.modules.admin.entity.Admin;
import com.dms.modules.admin.service.AdminService;
import com.dms.modules.merchant.entity.Merchant;
import com.dms.modules.merchant.service.MerchantService;
import com.dms.modules.user.entity.User;
import com.dms.modules.user.mapper.UserMapper;
import com.dms.modules.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/v1/admin")
@Api(tags = "管理员接口")
@Validated
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private UserService userService;

//    // 认证相关接口
//    @PostMapping("/auth/login")
//    @ApiOperation(value = "管理员登录", notes = "使用用户名和密码进行登录认证,返回JWT token")
//    public ApiResponse<AdminLoginResponse> login(@RequestBody @Validated AdminLoginRequest request) {
//        log.info("管理员登录请求: {}", request.getUsername());
//        try {
//            Admin admin = adminService.getByUsername(request.getUsername());
//            if (admin == null) {
//                log.warn("管理员 {} 不存在", request.getUsername());
//                return ApiResponse.validateFailed("用户名或密码错误");
//            }
//
//            if (!passwordEncoder.matches(request.getPassword(), admin.getPassword())) {
//                log.warn("管理员 {} 密码错误", request.getUsername());
//                return ApiResponse.validateFailed("用户名或密码错误");
//            }
//
//            if (admin.getStatus() == null || admin.getStatus() != 1) {
//                log.warn("管理员 {} 状态异常: {}", request.getUsername(), admin.getStatus());
//                return ApiResponse.validateFailed("账号已被禁用");
//            }
//
//            Long roleId = null;
//            if (admin.getUserId() != null) {
//                User user = userMapper.selectById(admin.getUserId());
//                if (user != null) {
//                    roleId = user.getRoleId();
//                }
//            }
//
//            String accessToken = jwtTokenProvider.generateToken(
//                new UsernamePasswordAuthenticationToken(admin, null, admin.getAuthorities())
//            );
//            String refreshToken = jwtTokenProvider.generateToken(
//                new UsernamePasswordAuthenticationToken(admin, null, admin.getAuthorities())
//            );
//
//            AdminLoginResponse response = AdminLoginResponse.builder()
//                .accessToken(accessToken)
//                .refreshToken(refreshToken)
//                .tokenType("Bearer")
//                .expiresIn(jwtTokenProvider.getAccessTokenExpiration())
//                .adminId(admin.getId())
//                .username(admin.getUsername())
//                .nickname(admin.getNickname())
//                .avatar(admin.getAvatar())
//                .email(admin.getEmail())
//                .phone(admin.getPhone())
//                .status(admin.getStatus())
//                .roleId(roleId)
//                .build();
//
//            log.info("管理员 {} 登录成功", request.getUsername());
//            return ApiResponse.success(response);
//        } catch (Exception e) {
//            log.error("管理员 {} 登录时发生异常: {}", request.getUsername(), e.getMessage(), e);
//            return ApiResponse.businessFailed("登录失败,请稍后重试");
//        }
//    }
//
//    @PostMapping("/auth/logout")
//    @ApiOperation(value = "管理员登出", notes = "管理员登出系统")
//    @PreAuthorize("hasRole('ADMIN')")
//    public ApiResponse<Void> logout() {
//        try {
//            // 清除当前用户的认证信息
//            SecurityContextHolder.clearContext();
//            log.info("管理员登出成功");
//            return ApiResponse.success();
//        } catch (Exception e) {
//            log.error("管理员登出时发生异常: {}", e.getMessage(), e);
//            return ApiResponse.businessFailed("登出失败,请稍后重试");
//        }
//    }

    // 管理员管理接口
    @GetMapping("/info")
    @ApiOperation("获取管理员信息")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse getAdminInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return ApiResponse.success(authentication.getPrincipal());
    }

    @PostMapping("/users")
    @ApiOperation(value = "创建管理员", notes = "创建新的管理员账号")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Long> createAdmin(@RequestBody @Validated AdminCreateDTO adminDTO) {
        log.info("创建管理员: {}", adminDTO.getUsername());
        
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDTO, admin);
        
        Admin createdAdmin = adminService.createAdmin(admin);
        return ApiResponse.success(createdAdmin.getId());
    }

    @GetMapping("/users")
    @ApiOperation("获取用户列表")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<List<User>> getUserList() {
        return ApiResponse.success(adminService.getUserList());
    }

    @PutMapping("/users/{id}/status")
    @ApiOperation("更新用户状态")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse updateUserStatus(@PathVariable Long id, @RequestParam Integer status) {
        adminService.updateUserStatus(id, status);
        return ApiResponse.success();
    }

    // 商家管理接口
    //搜索商家
    @GetMapping("/merchants/search")
    @ApiOperation("搜索商家")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<List<Merchant>> searchMerchants(@RequestParam String keyword) {
        List<Merchant> merchants = merchantService.searchMerchants(keyword);
        return ApiResponse.success(merchants);
    }
    
    @GetMapping("/merchants")
    @ApiOperation(value = "获取商家列表", notes = "分页获取商家列表")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<IPage<Merchant>> getMerchantList(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "keyword", required = false) String keyword) {
        log.info("获取商家列表: page={}, size={}, keyword={}", page, size, keyword);
        
        try {
            Page<Merchant> pageParam = new Page<>(page, size);
            IPage<Merchant> pageResult = merchantService.getMerchantPage(pageParam, keyword);
            return ApiResponse.success(pageResult);
        } catch (Exception e) {
            log.error("获取商家列表异常", e);
            return ApiResponse.businessFailed("获取商家列表失败: " + e.getMessage());
        }
    }
    //获取非审核通过的商家列表（待审核和已拒绝）
    @GetMapping("/merchants/non-approved")
    @ApiOperation("获取非审核通过的商家列表（包括待审核和已拒绝的商家）")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<List<Merchant>> getNonApprovedMerchants() {
        List<Merchant> merchants = merchantService.getNonApprovedMerchants();
        return ApiResponse.success(merchants);
    }
    @GetMapping("/merchants/{id}")
    @ApiOperation(value = "获取商家详情", notes = "根据ID获取商家详情")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Merchant> getMerchantDetail(@PathVariable("id") Long id) {
        log.info("获取商家详情: id={}", id);
        
        Merchant merchant = merchantService.getById(id);
        if (merchant == null) {
            return ApiResponse.validateFailed("商家不存在");
        }
        
        return ApiResponse.success(merchant);
    }
    
    //审核商家
    @PostMapping("/merchants/{id}/audit")
    @ApiOperation(value = "审核商家", notes = "管理员审核商家申请")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Boolean> auditMerchant(
            @PathVariable("id") Long id,
            @RequestParam("status") Integer status,
            @RequestParam(value = "comment", required = false) String comment) {
        log.info("管理员审核商家: id={}, status={}, comment={}", id, status, comment);
        
        if (status == null || (status != 1 && status != 2)) {
            return ApiResponse.validateFailed("审核状态只能是1(通过)或2(拒绝)");
        }
        
        try {
            Merchant merchant = merchantService.getById(id);
            if (merchant == null) {
                return ApiResponse.validateFailed("商家不存在");
            }
            
            merchant.setAuditStatus(status);
            merchant.setAuditComment(comment);
            merchant.setAuditTime(new Date());
            
            if (status == 1) {
                merchant.setStatus(1);
                if (merchant.getUserId() != null) {
                    merchantService.updateUserRole(merchant.getUserId(), 2L);
                }
            }
            
            boolean result = merchantService.updateById(merchant);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("审核商家异常", e);
            return ApiResponse.businessFailed("审核失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/merchants/{id}/status")
    @ApiOperation(value = "更新商家状态", notes = "启用或禁用商家账号")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Boolean> updateMerchantStatus(
            @PathVariable("id") Long id,
            @RequestParam("status") Integer status) {
        log.info("更新商家状态: id={}, status={}", id, status);
        
        if (status == null || (status != 0 && status != 1)) {
            return ApiResponse.validateFailed("状态只能是0(禁用)或1(启用)");
        }
        
        try {
            boolean result = merchantService.updateStatus(id, status);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("更新商家状态异常", e);
            return ApiResponse.businessFailed("更新商家状态失败: " + e.getMessage());
        }
    }


} 